/*
 * @Author: Lin Hongwei
 * @Date: 2022-10-17 23:01:21
 * @LastEditTime: 2022-10-31 18:56:14
 * @LastEditors: Lin Hongwei
 * @email: 1365755396@qq.com
 * @CSDN: https://blog.csdn.net/weixin_45429409
 * @Description: 用户接口控制器
 */
const { sign } = require('jsonwebtoken');
const { query, create, queryUser } = require('../service/users.service');
const { TOKEN_KEY, TOKEN_OUT_TIME } = require('../utils/constant');
const { userLoginError, userRegisterError } = require('../utils/errType');
class UserController {
  async getUserInfo(ctx, next) {
    try {
      // const whereSql = "where ?";
      // const res = await queryUser(ctx.params, whereSql);
      const res = await query(ctx.params);
      ctx.success(res[0])
    } catch (err) {
      ctx.fail("查询用户信息失败！")
    }
  }
  async getUserList(ctx, next) {
    try {
      const res = await queryUser();
      ctx.success(res)
    } catch (err) {
      console.log(err)
      ctx.fail({
        message: "查询失败"
      })
    }

  }
  async login(ctx, next) {
    try {
      const token = sign(
        Object.assign({}, ctx.state.userInfo),
        TOKEN_KEY,
        {
          issuer: "Macro-2",
          expiresIn: TOKEN_OUT_TIME
        }
      );
      // console.log(token)
      ctx.success({
        ...ctx.state.userInfo,
        token
      })
      // throw "自己抛出错误";
    } catch (err) {
      ctx.fail(userLoginError)
    }
  }
  async register(ctx, next) {
    try {
      let params = ctx.request.body;
      params.pass = params.cryptoPassword;
      delete params.cryptoPassword
      // const params = ctx.bodyParams;
      const res = await create(params);
      if (res.affectedRows > 0) return ctx.success({
        id: res.insertId,
        name: params.name,
        phone: params.phone
      });
      ctx.fail(userRegisterError)
    } catch (err) {
      ctx.fail(userRegisterError)
    }
  }
}



module.exports = new UserController()
